package com.reggie.intercepter;

import com.reggie.util.JwtUtil;
import com.reggie.util.ThreadLocalUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;
import java.util.concurrent.TimeUnit;

@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String url = request.getRequestURL().toString();
        String userInfo1 = (String) request.getSession().getAttribute("userInfo1");
        String userInfo2 = (String) request.getSession().getAttribute("userInfo2");
        if (userInfo1==null && userInfo2==null){
            if (url.contains("backend")){
                response.sendRedirect(request.getContextPath()+"/backend/page/login/login.html");
                return false;
            }
            response.sendRedirect(request.getContextPath()+"/front/page/login.html");
            return false;
        }
        String token = (userInfo1==null) ? userInfo2 : userInfo1;
        if (stringRedisTemplate.opsForValue().get(token)==null){
            if (userInfo1==null){
                response.sendRedirect(request.getContextPath()+"/backend/page/login/login.html");
                return false;
            }
            response.sendRedirect(request.getContextPath()+"/front/page/login.html");
            return false;
        }
        Map<String, Object> claims = JwtUtil.parseToken(token);
        ThreadLocalUtil.set(claims);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        ThreadLocalUtil.remove();
    }
}
